package org.lqfan.controller;

import org.lqfan.controller.viewobject.ItemVO;
import org.lqfan.error.BusinessException;
import org.lqfan.error.EmBusinessError;
import org.lqfan.response.CommonReturnType;
import org.lqfan.service.ItemService;
import org.lqfan.service.model.ItemModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/item")
@CrossOrigin(allowCredentials="true", allowedHeaders="*")
public class ItemController {

    @Autowired
    private ItemService itemService;


    @PostMapping(value = "create")
    @ResponseBody
    public CommonReturnType createItem(@RequestParam(name = "title")String title,
                                       @RequestParam(name = "price") BigDecimal price,
                                       @RequestParam(name = "description")String description,
                                       @RequestParam(name = "imgUrl")String imgUrl,
                                       @RequestParam(name = "stock")Integer stock) throws BusinessException {

        ItemModel itemModel = new ItemModel();
        itemModel.setTitle(title);
        itemModel.setPrice(price);
        itemModel.setDescription((description));
        itemModel.setStock(stock);
        itemModel.setImgUrl(imgUrl);

        ItemModel createItemReturnModel = itemService.createItem(itemModel);

        ItemVO itemVO = convertVOFromModel(createItemReturnModel);

        return CommonReturnType.create(itemVO);
    }

    @GetMapping(value = "list")
    @ResponseBody
    public CommonReturnType listItem() {
        List<ItemModel> itemModelList = itemService.getListItem();

        if(itemModelList == null) {
            return null;
        }

        List<ItemVO> itemVOList = itemModelList.stream().map(itemModel -> {
            ItemVO itemVO = this.convertVOFromModel(itemModel);
            return itemVO;
        }).collect(Collectors.toList());

        return CommonReturnType.create(itemVOList);
    }

    @GetMapping(value = "detail")
    @ResponseBody
    public CommonReturnType getItemDetail(@RequestParam(name = "id")Integer itemId) throws BusinessException {
        ItemModel itemModel = itemService.getItemById(itemId);
        if(itemModel == null) {
            throw new BusinessException(EmBusinessError.ITEM_NOT_EXIST);
        }
        ItemVO itemVO = this.convertVOFromModel(itemModel);

        return CommonReturnType.create(itemVO);
    }

    private ItemVO convertVOFromModel(ItemModel itemModel) {
        ItemVO itemVO = new ItemVO();
        BeanUtils.copyProperties(itemModel, itemVO);

        return itemVO;
    }
}
